import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> {//按第一个元素排序
            return a[0] - b[0];
        });

        List<int[]> list = new ArrayList<>();

        int left = intervals[0][0], right = intervals[0][1];

        int len = intervals.length;
        for (int i = 1; i < len; i++) {
            int a = intervals[i][0];
            int b = intervals[i][1];
            if (a <= right) {
                right = Math.max(right, b);
            } else {
                list.add(new int[]{left, right});//合并前一个
                left = a;
                right = b;
            }
        }

        list.add(new int[]{left, right});

        return list.toArray(new int[0][]);
    }
}
